-- curl -i '127.0.0.1:6699/api/tt/thread_semaphore'
 local F    = require "base_funs"

local semaphore = require "ngx.semaphore"

local sema = semaphore.new()


-- p3
ngx.say("count: ", sema:count())  -- count: 0

local function handler(id)
    
    local ok, err = sema:wait(2)
    if not ok then
        ngx.say("err: ", err)
    else
        ngx.say("wait success id==" .. tostring(id) )
    end
end

local co1 = ngx.thread.spawn(handler)
local co2 = ngx.thread.spawn(handler)

ngx.say("count: ", sema:count())  -- count: -2

sema:post(1)

ngx.say("count: ", sema:count())  -- count: -1

sema:post(2)

ngx.say("count: ", sema:count())  -- count: 1
-----END-------------


-- p2
local outputs = {}
local i = 1

local function out(s)
    outputs[i] = s
    i = i + 1
end

local function handler()
    out("timer thread: sleeping for a little while...")

    ngx.sleep(1.2)  -- wait a bit

    out("timer thread: posting on sema...")

    sema:post(1)
end

assert(ngx.timer.at(0, handler))

out("main thread: waiting on sema...")

local ok, err = sema:wait(1.5)  -- wait for a second at most
if not ok then
    out("main thread: failed to wait on sema: ", err)
else
    out("main thread: waited successfully.")
end

out("main thread: end.")

ngx.say(table.concat(outputs, "\n"))
-----END-------------

-- p1
-- local function handler()
--     ngx.say("sub thread: waiting on sema...")

--     local ok, err = sema:wait(5)  -- wait for a second at most

--     if not ok then
--         ngx.say("sub thread: failed to wait on sema: ", err)
--     else
--         ngx.say("sub thread: waited successfully.")
--     end

--     ngx.say("sub thread: handler...")
-- end



-- local co = ngx.thread.spawn(handler)
-- local co2 = ngx.thread.spawn(handler)



-- ngx.say("main thread: sleeping for a little while...")

-- ngx.sleep(0.1)  -- wait a bit

-- ngx.say("main thread: posting to sema...")

-- sema:post(1)
-- sema:post(1)

-- ngx.say("main thread: end.")
-----END-------------